import {AdminLoginService} from '@/api/login.js'

import {ref} from 'vue';
import {defineStore} from 'pinia'
import {ElMessage} from "element-plus";
import useAdminrouter from "@/router/index.js";

export const useAdminStore = defineStore('adminuser', {
        state: () => ({
            admin_id: '',
            admin_username: '',
            admin_password: '',
            admin_token: ''
        }),
        getters: {},
        actions: {
            async Login(loginForm) {
                // 后台管理系统登入录入token
                await AdminLoginService(loginForm)
                    .then((response) => {
                            const router = useAdminrouter
                            console.log("pinia里面的result", response.data)
                            if (response.data.code === 2000) {
                                this.$patch((state) => {
                                    state.admin_id = response.data.userId
                                    state.admin_username = response.data.user_name
                                    state.admin_password = response.data.password
                                    state.admin_token = response.data.token
                                    console.log('已经将token存到pinia里面了', state)
                                })
                                localStorage.setItem('admin_id', response.data.userId)
                                localStorage.setItem('admin_username', response.data.user_name)
                                localStorage.setItem('admin_token', response.data.token)
                            }
                            // ElMessage.success(response.data.msg)
                        }
                    ).catch((error) => {
                        console.log('error')
                        router.push({path:'/login'})
                    })
            },
            // 后台登出，清除token
            async Logout() {
                this.$patch((state) => {
                    state.admin_id = ''
                    state.admin_username = ''
                    state.admin_password = ''
                    state.admin_token = ''
                })
                localStorage.removeItem('admin_id')
                localStorage.removeItem('admin_username')
                localStorage.removeItem('admin_token')
                localStorage.removeItem('adminuser')
            },
        },
        persist: true
    }
)

